package com.motong.gongdan.config.mqtt;

import com.motong.gongdan.constant.CommonConstant;
import com.motong.gongdan.entity.DeviceInfo;
import com.motong.gongdan.service.DeviceInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

@Configuration
@Slf4j
public class MqttProviderInit {

    @Resource
    private MqttProviderConfig mqttProviderConfig;


    @Resource
    private DeviceInfoService deviceInfoService;


    @PostConstruct
    public void initSubscribe() {
        System.out.println("开始自动订阅");
        List<DeviceInfo> deviceInfos = deviceInfoService.list();
        deviceInfos.forEach(i -> {
            if (StringUtils.hasLength(i.getRealDeviceSn())) {
                try {
                    mqttProviderConfig.subscribe(CommonConstant.MQTT_PREFIX.concat(i.getRealDeviceSn()), 2);
                } catch (Exception e) {
                    log.error("订阅失败订阅主题为{}", CommonConstant.MQTT_PREFIX.concat(i.getRealDeviceSn()));
                }

            }
        });
    }

}
